package com.leyantech.ecp.agenx.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

/**
 * @author eahau, {@literal <yixiao.wang@leyantech.com>}
 * @date 2021-04-01.
 */
public final class JsonUtils {

  private JsonUtils() {
  }

  public static final JsonParser JSON_PARSER = new JsonParser();

  public static final Gson GSON = new GsonBuilder()
      .disableHtmlEscaping()
      .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC)
      .create();

  public static <T> T fromJson(String json, Class<T> clz) {
    return GSON.fromJson(json, clz);
  }

  public static <T> T fromJson(String json, Type type) {
    return GSON.fromJson(json, type);
  }

  public static <T> T fromJson(String json, TypeToken<T> typeToken) {
    return GSON.fromJson(json, typeToken.getType());
  }

  public static String toJson(Object o) {
    return GSON.toJson(o);
  }

  public static Object lazyToString(Object obj) {
    return new Object() {
      @Override
      public String toString() {
        return toJson(obj);
      }
    };
  }


}
